package com.zl.web.action;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.opensymphony.xwork2.ActionContext;

//import org.apache.struts2.ServletActionContext;
//import org.springframework.web.context.WebApplicationContext;
//import org.springframework.web.context.support.WebApplicationContextUtils;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.util.ValueStack;

import com.zl.domain.Customer;
import com.zl.domain.Dict;
import com.zl.domain.PageBean;
import com.zl.service.CustomerService;
import com.zl.utils.FastJsonUtil;
import com.zl.utils.UploadUtils;

public class CustomerAction extends ActionSupport implements ModelDriven<Customer> {

	private static final long serialVersionUID = 1L;

	/**
	 * 模型驱动
	 */
	private Customer customer = new Customer();

	public Customer getModel() {

		return customer;
	}

	// 提供service的成员属性
	private CustomerService customerService;

	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}

	// 属性驱动方式接收参数
	private Integer pageCode = 1; // 当前页
	private Integer pageSize = 2; // 每页显示的条数

	public void setPageCode(Integer pageCode) {
		this.pageCode = pageCode;
	}

	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}

	public String findByPage() {
		// 离线条件对象
		DetachedCriteria criteria = DetachedCriteria.forClass(Customer.class);

		if (pageCode == null) {
			pageCode = 1;
		}

		// 拼接查询条件
		String cust_name = customer.getCust_name();
		if (cust_name != null && !cust_name.trim().isEmpty()) {
			criteria.add(Restrictions.like("cust_name", "%" + cust_name + "%"));
		}
		Dict level = customer.getLevel();
		if (level != null && !level.getDict_id().trim().isEmpty()) {
			criteria.add(Restrictions.eq("level.dict_id", level.getDict_id()));
		}
		Dict source = customer.getSource();
		if (source != null && !source.getDict_id().trim().isEmpty()) {
			criteria.add(Restrictions.eq("source.dict_id", source.getDict_id()));
		}

		PageBean<Customer> page = customerService.findAllByPage(pageCode, pageSize, criteria);

		// 压栈 想前台传值
		ValueStack stack = ActionContext.getContext().getValueStack();
		// 栈顶是map<"page":page>
		stack.set("page", page);

		return "page";
	}

	public String addUI() {

		return "addUI";
	}
	
	/**
	 * 文件的上传，需要在CustomerAction中定义成员的属性，命名是有规则的
	 * Private File upload;     //表示要上传的文件   前端命名为upload这里就必须写成upload 命名和前端保持一致 不然就jj
	 * Private String uploadFileName;   //表示上传文件的名称
	 * Private String uploadContentType;  //表示上传文件的MIME类型
	 */
	private File upload;
	private String uploadFileName;
	private String uploadContentType;
	
	public void setUpload(File upload) {
		this.upload = upload;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	/**
	 * 新增客户
	 * @return
	 * @throws Exception 
	 */
	public String save() throws Exception {

		//文件上传
		if (uploadFileName != null) {
			System.out.println("文件名称："+uploadFileName);
			System.out.println("文件类型："+uploadContentType);
			
			String uuidName = UploadUtils.getUUIDName(uploadFileName);
			//文件上传到/Users/yezitaotao/Documents/Tomcate/apache-tomcat-7.0.73/webapps/upload
			String path = "/Users/yezitaotao/Documents/Tomcate/apache-tomcat-7.0.73/webapps/upload/";
			//创建file
			File file = new File(path+uuidName);
			FileUtils.copyFile(upload, file);
			
			//把文件上传路径保存的数据库中
			customer.setFilePath(path+uuidName);
			
		}
		
		customerService.save(customer);
		
		return "save";
	}
	/**
	 * 删除客户
	 * @return
	 */
	public String delete() {
		//先获取客户信息
		Customer c =customerService.findById(customer.getCust_id());
		if (c != null) {
			//删除客户相关的文件
			String filePath = c.getFilePath();
			//删除客户
			customerService.delete(c);
			if (filePath !=null && !filePath.trim().isEmpty()) {
				//删除客户相关的文件
				File file = new File(filePath);
				if (file.exists()) {
					
					file.delete();
				}
			}
		}
		return "delete";
	}
	/**
	 * 修改客户信息   UI
	 * 
	 */
	public String updateUI(){
		//默认customer是压栈的
		customer =customerService.findById(customer.getCust_id());
		
		System.out.println(customer.getCust_id());
		
		return "updateUI";
				
		
	}
	/**
	 * 修改客户信息
	 * @throws Exception 
	 * 
	 */
	public String update() throws Exception{
	
		if (uploadFileName != null) {
			//先删除旧的图片
			String oldpath = customer.getFilePath();
			if (oldpath != null && !oldpath.trim().isEmpty()) {
				File f = new File(oldpath);
				f.delete();				
			}
			//上传新图片
			String uuidName = UploadUtils.getUUIDName(uploadFileName);
			//文件上传到/Users/yezitaotao/Documents/Tomcate/apache-tomcat-7.0.73/webapps/upload
			String path = "/Users/yezitaotao/Documents/Tomcate/apache-tomcat-7.0.73/webapps/upload/";
			//创建file
			File file = new File(path+uuidName);
			FileUtils.copyFile(upload, file);
			
			//把文件上传路径保存的数据库中
			customer.setFilePath(path+uuidName);
		}
		//更新
		customerService.update(customer);
		return "update";
				
		
	}
	public String findAll(){
		List<Customer>list=customerService.findAll();
		String jsonString = FastJsonUtil.toJSONString(list);
		HttpServletResponse response = ServletActionContext.getResponse();
		FastJsonUtil.write_json(response, jsonString);
		return NONE;
	}
	
}
